package com.b2c.erp.extension_points;

import com.alibaba.fastjson.JSON;
import com.b2c.common.jdbc.DbUtil;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.PddWsClient;
import com.b2c.interfaces.ShopService;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddPmcUserPermitRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddPmcUserPermitResponse;
import com.pdd.pop.sdk.message.MessageHandler;
import com.pdd.pop.sdk.message.WsClient;
import com.pdd.pop.sdk.message.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;

@Component
public class PddWssCommandLineRunner implements CommandLineRunner {
    private static Logger log = LoggerFactory.getLogger(PddWssCommandLineRunner.class);
    @Autowired
    private ShopService shopService;
    @Override
    public void run(String... args) throws Exception {
        log.info("开始启动PddWssCommandLineRunner");
//        System.out.println(shopService);
        String clientId = DataConfigObject.getInstance().getPddClientId();
        String clientSecret = DataConfigObject.getInstance().getPddClientSecret();

        var shop = shopService.getShop(5);
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddPmcUserPermitRequest request = new PddPmcUserPermitRequest();
//        request.setTopics("pdd_trade_TradeConfirmed,pdd_refund_RefundCreated");
        request.setTopics("pdd_trade_TradeConfirmed,pdd_refund_RefundCreated,pdd_refund_RefundBuyerReturnGoods");

        PddPmcUserPermitResponse response = client.syncInvoke(request, shop.getSessionKey());
//        System.out.println(JsonUtil.transferToJson(response));

        log.info("pdd消息接口请求结果："+JsonUtil.transferToJson(response));
        String jdbcUrl = DataConfigObject.getInstance().getJdbcURL();
        String jdbcUser= DataConfigObject.getInstance().getJdbcUSER();
        String jdbcPwd = DataConfigObject.getInstance().getJdbcPASSWORD();


        WsClient ws = PddWsClient.getInstance().getWsClient();

        ws.setMessageHandler(new MessageHandler() {
            @Override
            public void onMessage(Message message) throws InterruptedException, IOException {

                DbUtil dbUtil = null;
                Connection conn = null;
                Statement stmt = null;

                try{
                    dbUtil =new DbUtil(jdbcUrl,jdbcUser,jdbcPwd);
                    conn = DbUtil.getConnection();
                    stmt = conn.createStatement();
                }catch (Exception e){
                    conn = null;
                    stmt = null;
                    log.info("数据库连接池初始化错误");
                }
                Integer shopId = 0;
                if(message.getMallID().longValue() == 100061591L){
                    shopId = 5;
                }
                String sql = "INSERT INTO dc_pdd_message SET mall_id="+message.getMallID()+",shopId="+shopId+",`type`='"+message.getType()+"',content='"+ JSON.toJSONString(message)+"'";
                if(stmt == null){
                    log.info("链接断开了");
                }
                try{
                    int r = stmt.executeUpdate(sql);
                    log.info("处理拼多多消息成功：" + JSON.toJSONString(message));
                }catch(Exception e){
                    log.info("处理拼多多消息失败：" + e.getMessage());
                }

            }
        });
    }
}
